package com.lock;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Lock_interruptibly implements Runnable {

    private int num = 1;
    private int size = 20;
    //重用锁
    private Lock lock  = new ReentrantLock();




    @Override
    public void run() {

        while (true) {

            this.start();
        }

    }
    public  void start() {
        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(num >= size){
            System.out.println("售卖结束");
            while (Thread.currentThread().isAlive()){
                System.out.println( Thread.currentThread().isInterrupted());
                System.out.println( Thread.currentThread().isAlive());
                System.out.println("回收妹子:"+Thread.currentThread().getName());
                Thread.currentThread().stop();
                Thread.currentThread().interrupt();
                System.out.println( Thread.currentThread().isInterrupted());
                System.out.println( Thread.currentThread().isAlive());
                break;
            }
            return;

        }


        try {



            System.out.println(Thread.currentThread().getName()+"加锁");


            System.out.println(String.format("时间:%s,售票妹子:%s，卖出第:%s 张票，还剩下:%s 张票",new Date(),Thread.currentThread().getName(),this.num,this.size-this.num));
            Thread.sleep(500);
            num ++ ;

        } catch (Exception e) {
            e.printStackTrace();

        }finally {
            lock.unlock();
            System.out.println(  Thread.currentThread().getName()+"解锁");
        }
    }

    public static void main(String[] args) {
        Lock_interruptibly three = new Lock_interruptibly();
        while (true){
            System.out.println("输入售卖妹妹");
            String girl  = new Scanner(System.in).next();

            Thread thread = new Thread(three,girl);
            thread.start();

        }
    }
}
